package help

import (
	"bytes"
	"fmt"
	"net/http"
	"strings"
)

type SSE struct {
	w http.ResponseWriter
}

func NewSSE(w http.ResponseWriter) *SSE {
	w.Header().Set("X-Accel-Buffering", "no")
	w.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	return &SSE{w: w}
}

func (tis *SSE) SendEventMessage(data string) error {
	return tis.SendEventMessage3(data, "", "")
}

func (tis *SSE) SendEventMessage2(data, event string) error {
	return tis.SendEventMessage3(data, event, "")
}

func (tis *SSE) SendEventMessage3(data, event, id string) error {
	w := tis.w

	var buffer bytes.Buffer

	if len(id) > 0 {
		buffer.WriteString(fmt.Sprintf("id: %s\n", strings.Replace(id, "\n", "", -1)))
	}

	if len(event) > 0 {
		buffer.WriteString(fmt.Sprintf("event: %s\n", strings.Replace(event, "\n", "", -1)))
	}

	if len(data) > 0 {
		lines := strings.Split(data, "\n")
		for _, line := range lines {
			buffer.WriteString(fmt.Sprintf("data: %s\n", line))
		}
	}
	buffer.WriteString("\n")

	_, err := w.Write(buffer.Bytes())
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}
	return err
}
